package com.basic.library.utils.audio;

import android.media.MediaRecorder;

import com.basic.library.base.BaseApplication;
import com.basic.library.utils.MyLog;

import java.io.File;

import static com.basic.library.base.BaseConstants.CACHE_AUDIO_PATH;

/**
 * @author yj
 * @description
 */

public class AudioManager {

    private MediaRecorder mRecorder;
    private final String mDirString = CACHE_AUDIO_PATH;
    private String mCurrentFilePathString;

    private boolean isPrepared;// 是否准备好了

    /**
     * 单例化的方法 1 先声明一个static 类型的变量a 2 在声明默认的构造函数 3 再用public synchronized static
     * 类名 newInstance() { if(a==null) { a=new 类();} return a; } 或者用以下的方法
     */

    /**
     * 单例化这个类
     */
    private static AudioManager mInstance = new AudioManager();

    public static AudioManager getInstance() {
        return mInstance;
    }

    public boolean isPrepared() {
        return isPrepared;
    }

    /**
     * 回调函数，准备完毕，准备好后，button才会开始显示录音框
     *
     * @author nickming
     */
    public interface AudioStageListener {
        void wellPrepared();
    }

    public AudioStageListener mListener;

    public AudioManager setOnAudioStageListener(AudioStageListener listener) {
        mListener = listener;
        return this;
    }

    // 准备方法
    public void prepareAudio() {
        try {
            release();// release释放一个mediarecorder
            // 一开始应该是false的
            isPrepared = false;

            File dir = new File(mDirString);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String fileNameString = generalFileName();
            File file = new File(dir, fileNameString);

            mCurrentFilePathString = file.getAbsolutePath();

            mRecorder = new MediaRecorder();
            // 设置输出文件
            mRecorder.setOutputFile(file.getAbsolutePath());
            // 设置meidaRecorder的音频源是麦克风
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            // 设置文件音频的输出格式为amr
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            // 设置音频的编码格式为amr
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

            // 设置录音文件的清晰度
            mRecorder.setAudioSamplingRate(44100);
            mRecorder.setAudioEncodingBitRate(192000); //192000  96000

            // 严格遵守google官方api给出的mediaRecorder的状态流程图
            mRecorder.prepare();
            MyLog.p("录音开启");
            MAudioManager.getInstance().initAudioManager(BaseApplication.getInstance().getApplicationContext());

            mRecorder.start();
            // 准备结束
            isPrepared = true;
            // 已经准备好了，可以录制了
            if (mListener != null) {
                mListener.wellPrepared();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            MAudioManager.getInstance().muteAudioFocus(false);
        }
    }

    /**
     * 随机生成文件的名称
     *
     * @return
     */
    public String generalFileName() {
        if (fileName != null)
            return "carPadChat_" + System.currentTimeMillis() + fileName;
//        return UUID.randomUUID().toString() + "Android.amr";
        return "auto888888_android.amr";
    }

    String fileName;

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    // 获得声音的level
    public int getVoiceLevel(int maxLevel) {
        // mRecorder.getMaxAmplitude()这个是音频的振幅范围，值域是1-32767
        if (isPrepared) {
            try {
                // 取证+1，否则去不到7
                return maxLevel * mRecorder.getMaxAmplitude() / 32768 + 1;
            } catch (Exception e) {
                // TODO Auto-generated catch block

            }
        }

        return 1;
    }

    // 释放资源
    public void release() {
        isPrepared = false;
        // 严格按照api流程进行
        try {
            MAudioManager.getInstance().muteAudioFocus(false);
            if (mRecorder != null) {
                try {
                    mRecorder.stop();
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                mRecorder.release();
                mRecorder = null;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 取消,因为prepare时产生了一个文件，所以cancel方法应该要删除这个文件，
    // 这是与release的方法的区别
    public void cancel() {
        release();
        if (mCurrentFilePathString != null) {
            File file = new File(mCurrentFilePathString);
            file.delete();
            mCurrentFilePathString = null;
        }

    }

    public String getCurrentFilePath() {
        // TODO Auto-generated method stub
        return mCurrentFilePathString;
    }

}
